package drds.global_transaction.resource_manager.proxy.resource_manager;

import com.alibaba.druid.pool.DruidDataSource;
import drds.global_transaction.api.api.Resource;
import drds.global_transaction.resource_manager.ResourceManager;
import drds.global_transaction.resource_manager.proxy.datasource.AbstractDataSourceProxy;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 一个数据源<DataSource>就是一个Resource,一个主从集群为一个Resource Group
 */
public class DataSourceProxy extends AbstractDataSourceProxy implements Resource
{

	private String resourceGroupId = "default";
	//
	private boolean registerResource = false;

	public DataSourceProxy(DruidDataSource druidDataSource)
	{
		super(druidDataSource);
	}

	public DataSourceProxy(DruidDataSource druidDataSource, String resourceGroupId)
	{
		super(druidDataSource);
		this.resourceGroupId = resourceGroupId;
	}

	@Override
	public ConnectionProxy getConnection() throws SQLException
	{
		registerResource();
		Connection connection = druidDataSource.getConnection();
		return new ConnectionProxy(this, connection);
	}

	@Override
	public ConnectionProxy getConnection(String username, String password) throws SQLException
	{
		throw new UnsupportedOperationException();
	}
	//

	/**
	 * 直接从<物理连接池>获取原生数据库连接
	 */
	public Connection getNativeConnection() throws SQLException
	{
		return druidDataSource.getConnection();
	}

	//
	@Override
	public String getResourceGroupId()
	{
		return resourceGroupId;
	}

	@Override
	public String getResourceId()
	{
		return druidDataSource.getUrl();
	}

	/**
	 * 当一个数据源开始连接数据库的时候需要向事务协调器注册一个资源管理器
	 */
	private void registerResource()
	{
		if (!registerResource)
		{
			ResourceManager.get().registerResource(this);
			registerResource = true;
		}
	}

}